<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #canvas {
            background: rebeccapurple;
        }
    </style>
</head>
<body>

<canvas id="canvas"></canvas>

<script>
    const canvas = document.getElementById('canvas')
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    const ctx = canvas.getContext('2d')

    class Sector {
        constructor(r = 200, startAngle = 0, endAngle = Math.PI / 2, color = 'red') {
            this.r = r
            this.startAngle = startAngle
            this.endAngle = endAngle
            this.color = color
            this.x = 0
            this.y = 0
        }

        draw(ctx) {
            const {x, y, r, startAngle, endAngle, color} = this
            ctx.save()
            ctx.beginPath()
            ctx.moveTo(x, y)
            ctx.arc(x, y, r, startAngle, endAngle)
            ctx.fillStyle = color
            ctx.fill()
            ctx.restore()
        }
    }

    const item = new Sector()
    item.x = canvas.width / 2
    item.y = canvas.height / 2
    item.draw(ctx)

    canvas.addEventListener('mousedown', (e) => {
        const mousePos = getPos(e)
        const delta = {
            x: mousePos.x - item.x,
            y: mousePos.y - item.y,
        }
        const {x, y} = delta

        // 算出距离圆心的距离
        const len = Math.sqrt(x * x + y * y)

        // 鼠标在圆半径内
        const bool1 = len < item.r
        // 鼠标到圆心弧度判断
        const dir = Math.atan2(y, x)

        const bool2 = dir > item.startAngle && dir < item.endAngle

        if (bool1 && bool2) {
            item.color = 'green'
        } else {
            item.color = 'yellow'
        }

        item.draw(ctx)
    })

    function getPos(event) {
        const {clientX, clientY} = event
        const {left, top} = canvas.getBoundingClientRect()
        //获取鼠标相对画布的坐标
        const [x, y] = [clientX - left, clientY - top]
        console.log(x, y)
        return {x, y}
    }
</script>
</body>
</html>
